package cc.laop.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class NettyServer {

	public void start(int port) {
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();

		ServerBootstrap boot = new ServerBootstrap();
		boot.group(boss, worker);
		boot.channel(NioServerSocketChannel.class);
		boot.option(ChannelOption.SO_BACKLOG, 128);
		// 通过NoDelay禁用Nagle,使消息立即发出去，不用等待到一定的数据量才发出去
		boot.option(ChannelOption.TCP_NODELAY, true);
		boot.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pll = ch.pipeline();
				pll.addLast(new ObjectEncoder());
				pll.addLast(
						new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
				pll.addLast(new NettyServerHandler());
			}
		});

		try {
			ChannelFuture cf = boot.bind(port).sync();
			if (cf.isSuccess()) {
				System.out.println("server start---------------");
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		NettyServer ns = new NettyServer();
		ns.start(9100);

		while (true) {
			// for (Map.Entry<String, SocketChannel> entity : ChannelManager
			// .getChannelMap().entrySet()) {
			// AskMsg am = new AskMsg();
			// am.setMessage("server ask.");
			// entity.getValue().writeAndFlush(am);
			// Thread.sleep(2000);
			// }
		}
	}

}
